(function(){
	
	if (!window.CJ) {
		window.CJ = {};
	}

	function loginView (userID) {
		$('#user').removeClass('').addClass('login').children('b').text(userID);
	}
	
	//내정보 버튼
	function Myinfo () {
		this.name = 'Myinfo';
		this.bindEvent();
		
		var userID = CJ.plugin.membership.getUserID();
		if (userID !== null) {
			loginView(userID);
		}
	}
	
	Myinfo.prototype = new EventCtl();
	Myinfo.prototype.bindEvent = function () {
		//hover
		var self = this;
		$('#user').on('click', function() {
			self.enter();
		});
		$('#user').on('mouseenter', function() {
			if(!CJ.isRightDetailEntry) {
				$('#global li').removeClass('focus');
				$('#user').addClass('focus');
				CJ.Scene.setDelegate(CJ.Scene["Myinfo"]);
			}
		});
	};
	Myinfo.prototype.down = function () {
		CJ.Scene.banner();
	};
	Myinfo.prototype.left = function () {
		$('#user').removeClass('focus');
		$('#global li').removeClass('focus');
		CJ.Scene.channel();
	};
	Myinfo.prototype.right = function () {
		CJ.Scene.search();
	};
	Myinfo.prototype.back = function () {
		$('#user').removeClass('focus');
		CJ.Scene.channel();
	};
	Myinfo.prototype.enter = function () {
		if (CJ.plugin.membership.isLogin()) {
			CJ.Scene.myinfoDetail();
		} else {
			CJ.plugin.membership.login(loginView, function() {
				console.log('login fail');
			});
		}
	};
	
	
	//내정보 상세
	function MyinfoDetail () {
		this.name = 'MyinfoDetail';
		this.rootID = '#mypage';
		this.rootElem = $(this.rootID + " .tab");
		this.bindEvent();
	}
	MyinfoDetail.prototype = new EventCtl();
	MyinfoDetail.prototype.bindEvent = function () {
		$('#playlistBtn').on('click', function() {
			$('#paylistBtn').removeClass('select focus');
			$(this).addClass('select focus');
			$('#mypage').removeClass().addClass('dep1');
		});
		$('#paylistBtn').on('click', function() {
			$('#playlistBtn').removeClass('select focus');
			$(this).addClass('select focus');
			$('#mypage').removeClass().addClass('dep2');
		});
		$(this.rootElem).on('mouseenter', 'li', function() {
			$(this).addClass('focus').siblings().removeClass('focus');
			$('#mypage .dep1 .focus').removeClass('focus');
			$('#mypage .dep2 .focus').removeClass('focus');
			CJ.Scene.setDelegate(CJ.Scene["MyinfoDetail"]);
		});
	};
	MyinfoDetail.prototype.left = function () {
		this.moveH('prev');
		$(this.rootID).removeClass().addClass('dep1');
	};
	MyinfoDetail.prototype.right = function () {
		this.moveH('next');
		$(this.rootID).removeClass().addClass('dep2');
	};
	MyinfoDetail.prototype.moveH = function (func) {
		var idx, now = $('li.select', this.rootElem),
			next = now[func]();
		if (next.length>0) {
			now.removeClass('select focus');
			next.addClass('select focus');
		}
		//this.enter();
	};
	MyinfoDetail.prototype.up = function () {
		CJ.Scene.myinfo();
	};
	MyinfoDetail.prototype.down = function () {
		this.enter();
	};
	MyinfoDetail.prototype.back = function () {
		CJ.Scene.myinfo();
	};
	MyinfoDetail.prototype.enter = function () {
		//
		var now = $('li.select', this.rootElem);
		if (now.attr('id') == 'playlistBtn') {
			CJ.Scene.myPlayList();
		} else { //like 클릭
			CJ.Scene.myPayList();
		}
		$('.focus', this.rootElem).removeClass('focus');
	};
	
	

	//내 플레이 리스트
	function MyPlayList () {
		this.name = 'MyPlayList';
		this.rootID = '#mypage .dep1';
		this.rootElem = $("#myplaylist");
		this.renderStartIdx = 0;
		this.renderRange = 4;
		this.bindEvent();
	}
	MyPlayList.lists = [];
	MyPlayList.totalCount = 0;
	MyPlayList.pageSize = 50;
	MyPlayList.pageNo = 0;
	MyPlayList.checkData = function () {
		if (this.totalCount == 0) {
			this.getData();
		}
	};
	MyPlayList.getData = function () {
		CJ.HttpJson.get({
			type: 'PLAYLIST',
			param: {
				userID: CJ.plugin.membership.getUserID(),
				pageSize: this.pageSize,
				pageNo: this.pageNo+1
			},
			success: function (json) {
				MyPlayList.successCB(json);
			}
		});
	};
	MyPlayList.successCB = function (json) {
		this.lists  = this.lists.concat(json.playlist);
		this.totalCount = parseInt(json.total_count);
		this.totalPage =  parseInt(json.page_info.total_page);
		this.pageNo =  parseInt(json.page_info.page);
		if (json.page_info.page == 1) {
			CJ.Scene["MyPlayList"].render();
		}
	};
	MyPlayList.getMore = function () {
		if (this.totalPage != this.pageNo) {
			this.getData();
		}
	};
	MyPlayList.prototype = new EventCtl();
	MyPlayList.prototype.bindEvent = function () {
		var self = this;
		$(this.rootID + ' .btn_prev').on('click', function() {
			self.enter();
		});
		$(this.rootID + ' .btn_next').on('click', function() {
			self.enter();
		});
		$(this.rootElem).on('click', 'li', function() {
			self.enter();
		});
		
		$(this.rootID + ' .btn_prev, '+ this.rootID + ' .btn_next').on('mouseenter', function() {
			$('#mypage .dep1 .focus').removeClass('focus');
			$('#mypage .tab .focus').removeClass('focus');
			$(this).addClass('focus');
			CJ.Scene.setDelegate(CJ.Scene["MyPlayList"]);
		});
		$(this.rootElem).on('mouseenter', 'li', function() {
			$('#mypage .dep1 .focus').removeClass('focus');
			$('#mypage .tab .focus').removeClass('focus');
			$(this).addClass('focus');
			CJ.Scene.setDelegate(CJ.Scene["MyPlayList"]);
		});
	};
	MyPlayList.prototype.render = function (sIdx) {
		sIdx = sIdx || 0;
		var len = MyPlayList.lists.length;
		var range = this.renderRange;
		var arr = [];
		if (len < (range+sIdx) ){
			range = len - sIdx;
		}
		
		for (var i=0; i<range; i++) {
			arr.push(MyPlayList.lists[i+sIdx]);
		}
		this.renderStartIdx = sIdx ;
		
		$( this.rootElem ).html(
			$.render.myPlayListTemplate( arr )
		);
		this.pageNum(sIdx);
	};
	MyPlayList.prototype.pageNum = function(idx) {
		var total = MyPlayList.totalCount;
		$(this.rootID+' .btn>span').text(parseInt(idx+1)+'/'+total);
	};
	MyPlayList.prototype.extend = function() {
		MyPlayList.getMore();
	};
	MyPlayList.prototype.left = function () {
		this.moveH('prev');
	};
	MyPlayList.prototype.right = function () {
		this.moveH('next');
	};
	MyPlayList.prototype.moveH = function (downup) {
		this.extend();
		var now = $("li.focus", this.rootElem);
		var btn = $(this.rootID + " .btn.focus");
		var next = now[downup]();
		if (now.length>0) {
			if (next.length>0) {
				$("li", this.rootElem).removeClass('focus');
				next.addClass('focus');
			} else {
				$("li", this.rootElem).removeClass('focus');
				$(this.rootID + ' ' + (downup == 'next' ? '.btn_next' : '.btn_prev')).addClass('focus');
			}
		} else {
			if(btn.hasClass('btn_prev') && downup == 'next') {
				btn.removeClass('focus');
				$("li:first-child", this.rootElem).addClass('focus');
			} else if(btn.hasClass('btn_next') && downup == 'prev') {
				btn.removeClass('focus');
				$("li:last-child", this.rootElem).addClass('focus');
			}
		}
	};
	MyPlayList.prototype.up = function () {
		CJ.Scene.myinfoDetail();
	};
	MyPlayList.prototype.back = function () {
		CJ.Scene.myinfoDetail();
	};
	
	MyPlayList.prototype.enter = function () {
		var sIdx;
		var now = $("li.focus", this.rootElem);
		var btn = $(this.rootID + " .btn.focus");
		if (now.length>0) {
			this.viewVod();
		} else {
			this.extend();
			if(btn.hasClass('btn_prev')) {
				sIdx = this.renderStartIdx - this.renderRange;
			} else {
				sIdx = this.renderStartIdx + this.renderRange;
			}
			
			if(sIdx >= 0 && sIdx < MyPlayList.lists.length) {
				this.render(sIdx);
			}
		}
	};
	MyPlayList.prototype.viewVod = function () {
		//컨텐츠 선택
		var now = $("li.focus", this.rootElem);
		var title = now.children('h4').text();
		var eid = now.data('episodeid');
		var pid = now.data('programid');
		var cid = now.data('channelid');
		var likeCnt = now.data('likecount');
		
		var price;
		//과금 체크 및 과금 후 재생 요청 
		function vaildUser () { //과금유저
			//channel, program, episode 데이터 읽어 보기
			CJ.SubList.loadAllList(cid, pid, eid);
			//video 플레이
			VideoPlay(title, likeCnt, pid, eid);
		}
		function invalidUser () {//미과금유저
			CJ.Scene.billing(pid, eid, price, vaildUser);
		}
		// 가격 정보 & 성인 등급 조회
		CJ.plugin.billing.getPrice(pid, eid, function (json) {
			price = {"vodprice" : json.vodprice, "seriesprice" : json.seriesprice, "flatprice" : json.flatprice};
			var grade = json.grade;
			
			CJ.plugin.billing.checkBilling( pid, eid,
								vaildUser,
								invalidUser,
								grade);
		});
	};
	
	function VideoPlay (title, likeCnt, pid, eid) { //과금유저
		$('#vod>h3>span').text(title);
		$('#vod>h3 .num').text(likeCnt);
		CJ.Video.play(pid, eid, CJ.Scene.myPlayList);
	}
	
	
	
	//내 결재 리스트
	function MyBillingList () {
		this.name = 'MyBillingList';
		this.rootID = '#mypage .dep2';
		this.rootElem = $("#myplaylist");
		this.bindEvent();
	}
	MyBillingList.lists = [];
	MyBillingList.totalCount = 0;
	MyBillingList.pageSize = 50;
	MyBillingList.pageNo = 0;
	MyBillingList.checkData = function () {
		if (this.totalCount == 0) {
			this.getData();
		}
	};
	MyBillingList.getData = function () {
		CJ.HttpJson.get({
			type: 'PAYMENTLIST',
			param: {
				userID: "1",// CJ.plugin.membership.getUserID(),
				pageSize: this.pageSize,
				pageNo: this.pageNo+1
			},
			success: function (json) {
				MyBillingList.successCB(json);
			}
		});
	};
	MyBillingList.successCB = function (json) {
		this.lists  = this.lists.concat(json.paymentlist);
		/*
		this.lists.push(json.paymentlist[0]);
		this.lists.push(json.paymentlist[0]);
		this.lists.push(json.paymentlist[0]);
		this.lists.push(json.paymentlist[0]);
		this.lists.push(json.paymentlist[0]);
		this.lists.push(json.paymentlist[0]);
		this.lists.push(json.paymentlist[0]);
		this.lists.push(json.paymentlist[0]);
		this.lists.push(json.paymentlist[0]);
		this.lists.push(json.paymentlist[0]);
		this.lists.push(json.paymentlist[0]);
		this.lists.push(json.paymentlist[0]);
		this.lists.push(json.paymentlist[0]);
		this.lists.push(json.paymentlist[0]);
		*/
		
		this.totalCount = parseInt(json.total_count);
		this.totalPage =  parseInt(json.page_info.total_page);
		this.pageNo =  parseInt(json.page_info.page);
		if (json.page_info.page == 1) {
			CJ.Scene["MyBillingList"].render();
		}
	};
	MyBillingList.getMore = function () {
		if (this.totalPage != this.pageNo) {
			this.getData();
		}
	};
	MyBillingList.prototype = new EventCtl();
	MyBillingList.prototype.bindEvent = function () {
		var self = this;
		$(this.rootID + ' .btn_prev').on('click', function() {
			self.enter();
		});
		$(this.rootID + ' .btn_next').on('click', function() {
			self.enter();
		});
		
		$(this.rootID + ' .btn_prev, '+ this.rootID + ' .btn_next').on('mouseenter', function() {
			$('#mypage .dep2 .focus').removeClass('focus');
			$('#mypage .tab .focus').removeClass('focus');
			$(this).addClass('focus');
			CJ.Scene.setDelegate(CJ.Scene["MyBillingList"]);
		});
	};
	MyBillingList.prototype.render = function (sIdx) {
		sIdx = sIdx || 0;
		var len = MyBillingList.lists.length;
		var range = 4;
		var arr = [];
		if (len < (range+sIdx) ){
			range = len - sIdx;
		}
		
		for (var i=0; i<range; i++) {
			arr.push(MyBillingList.lists[i+sIdx]);
		}
		this.sIdx = sIdx ;
		
		$('#billingList td').text('');
		$('#billingList tr.paylist').each(function(idx, elem) {
			if (idx < arr.length) {
				var td = $(elem).children('td');
				td.eq(0).text(CJ.util.getDateStr(arr[idx].paymentdate, '.'));
				td.eq(1).text(arr[idx].paymentdesc);
				td.eq(2).text(arr[idx].paymentprice);
				td.eq(3).text(CJ.util.getDateStr(arr[idx].paymentexpirdate, '.'));
			}
		});
		
		this.pageNum(sIdx);
	};
	MyBillingList.prototype.pageNum = function(idx) {
		var total = MyBillingList.totalCount;
		$(this.rootID+' .btn>span').text(parseInt(idx+1)+'/'+total);
	};
	MyBillingList.prototype.extend = function() {
		MyBillingList.getMore();
	};
	
	MyBillingList.prototype.left = function () {
		this.moveH('prev');
	};
	MyBillingList.prototype.right = function () {
		this.moveH('next');
	};
	MyBillingList.prototype.moveH = function (downup) {
		this.extend();
		var btn = $(this.rootID + " .btn.focus");
		btn.removeClass('focus');
		$(this.rootID + ' ' + (downup == 'next' ? '.btn_next' : '.btn_prev')).addClass('focus');
	};
	MyBillingList.prototype.up = function () {
		CJ.Scene.myinfoDetail();
	};
	MyBillingList.prototype.back = function () {
		CJ.Scene.myinfoDetail();
	};
	MyBillingList.prototype.enter = function () {
		this.extend();
		var btn = $(this.rootID + " .btn.focus");
		if(btn.hasClass('btn_prev')) {
			sIdx = this.sIdx - 4;
		} else {
			sIdx = this.sIdx + 4;
		}
		
		if(sIdx >= 0 && sIdx < MyBillingList.lists.length) {
			this.render(sIdx);
		}
	};


	$.extend(CJ.Scene, {
							myinfo: function(){
								CJ.isRightDetailEntry = false;
								$("#wrap").removeClass().addClass('ch');
								$('#global li').removeClass('focus');
								$('#user').addClass('focus');
								$("#mask").hide();
								this.setDelegate(this["Myinfo"]);
							},
							myinfoDetail : function () {
								CJ.isRightDetailEntry = true;
								MyPlayList.checkData();
								MyBillingList.checkData();
								$("#wrap").removeClass().addClass('ch mypage');
								$('#global li').removeClass('focus');
								$("#mask").show();
								$('#mypage .tab .select').addClass('focus');
								$('#mypage .dep1 .focus').removeClass('focus');
								$('#mypage .dep2 .focus').removeClass('focus');
								this.setDelegate(this["MyinfoDetail"]);
							},
							myPlayList : function () {
								$("#wrap").removeClass().addClass('ch mypage');
								if ($('#myplaylist li.focus').length == 0) {
									$('#myplaylist li:first-child').addClass('focus');
								}
								this.setDelegate(this["MyPlayList"]);
							},
							myPayList : function () {
								$('#mypage .dep2 .btn_next').addClass('focus');
								this.setDelegate(this["MyBillingList"]);
							}
						});

	$(document).ready(function(){
		CJ.Scene["Myinfo"] = new Myinfo();
		CJ.Scene["MyinfoDetail"] = new MyinfoDetail();
		CJ.Scene["MyPlayList"] = new MyPlayList();
		CJ.Scene["MyBillingList"] = new MyBillingList();
		
		
		//test용으로 logout을 공지사항 버튼에서 처리
		$('#global .notice').on('click', function(){
			CJ.plugin.membership.logout();
			$('#user').removeClass('').addClass('logout').children('b').text('');
		});
		//test용으로 logout을 공지사항 버튼에서 처리
		
	});

})();